<!-- 订单管理-客户订单-销售订单 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="add">
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default>新建销售订单</template>
      </a-button>
    </template>
  </pageHeader>
  <div class="sales-order">
    <a-tabs v-model="getListType" @change="getSearchType" type="line">
      <a-tab-pane :key="1" title="待确认"> </a-tab-pane>
      <a-tab-pane :key="0" title="已确认"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-search
          search-button
          v-model="NumberSearch"
          :style="{ width: '220px' }"
          placeholder="订单号"
          @search="Search"
        />
        <a-input-search
          search-button
          v-model="clientCompanyNameVal"
          :style="{ width: '220px' }"
          placeholder="客户"
          @search="Search"
        />
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning" @click="OrderDerive">
          <template #icon>
            <icon-export :rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <!-- <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        > -->
        <a-button type="primary" v-if="isShow" @click="modOrderState">
          <template #default>确认</template>
        </a-button>
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <TableTurn
      :args="{
        rowSelection:
          getListType === 1
            ? {
                type: 'checkbox',
              }
            : false,
        bordered: {
          headerCell: true,
        },
        stripe: true,
      }"
      :table-data="getData"
      ref="tableRef"
    >
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :title="item.name"
        :data-index="item.code"
        :key="item.code"
        :width="150"
        align="center"
      >
        <!-- 计划开始时间 -->
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <!-- 计划开始时间 -->
        <template v-else-if="item.code === 'totalPrice'" #cell="{ record }">
          ￥{{ record.totalPrice }}
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        fixed="right"
        title="订单确认状态"
        align="center"
      >
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderConfirmStatus.filter(
                (ele) => ele.id === record.state
              )[0]?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderConfirmStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{
              orderConfirmStatus.filter((ele) => ele.id === record.state)[0]
                ?.value
            }}
          </div>
        </template>
      </a-table-column>
      <a-table-column
        v-if="getListType !== 1"
        :width="150"
        fixed="right"
        title="订单执行状态"
        align="center"
      >
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderExecuteStatus.filter(
                (ele) => ele.id === record.state
              )[0]?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderExecuteStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{
              orderExecuteStatus.filter((ele) => ele.id === record.state)[0]
                ?.value
            }}
          </div>
        </template>
      </a-table-column>
      <a-table-column
        v-if="getListType === 1"
        :width="100"
        fixed="right"
        title="操作"
        align="center"
      >
        <template #title>
          <span>操作</span>
          <!-- <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              style="cursor: pointer; position: absolute; top: 7px; right: 40px"
              @click="showFormHeaderSetting"
            />
          </a-tooltip> -->
        </template>
        <template #cell="{ record }">
          <!-- <a-button
            v-if="record.state === 1"
            type="text"
            @click="goDetail(record.id, record.state)"
            >订单详情</a-button
          > -->
          <!-- <a-popconfirm
            v-if="record.state === 1"
            @ok="deleteItem(record.id)"
            content="确定删除吗"
            type="error"
          >
            <a-button
              type="text"
              :style="{
                color: 'red',
              }"
              >删除</a-button
            >
          </a-popconfirm> -->

          <a-tooltip v-if="record.state === 1" content="编辑">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetail(record.id, record.state)"
            />
          </a-tooltip>
          <a-tooltip content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="deleteItem(record.id)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </div>
  <FormHeaderSetting
    title="待确认订单列表表头设置"
    v-model:visible="formHeaderSettingVisible"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    GetClientOrder,
    GetHeaderSettings,
    putHeaderSettings,
    putClientOrder,
    DeleteClientOrder,
    GetOrderDeriveExcel,
    modState,
  } from '@/api/order-management/client-order';

  const NumberSearch = ref();
  const clientCompanyNameVal = ref();
  const StateVal = ref();
  const router = useRouter();
  const title: string = '待确认订单';
  const breadCrumb: string[] = ['订单管理', '客户订单', '待确认订单'];
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  const modelCauseVisible = ref(false);
  const isShow = ref(true);

  const orderConfirmStatus = [
    { id: 1, value: '待确认', backgroundColor: '#cccccc' },
    { id: 2, value: '已确认', backgroundColor: '#009933' },
    { id: 3, value: '已确认', backgroundColor: '#009933' },
    { id: 4, value: '已确认', backgroundColor: '#009933' },
  ];
  const orderExecuteStatus = [
    { id: 1, value: '待执行', backgroundColor: '#4e8bfb' },
    { id: 2, value: '待执行', backgroundColor: '#4e8bfb' },
    { id: 3, value: '执行中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '已完成', backgroundColor: '#009933' },
  ];
  // const args = reactive({
  //   rowSelection: {
  //     type: 'checkbox',
  //     showCheckedAll: true,
  //     onlyCurrent: false,
  //   },
  // });
  const userState = ref(); // 储存状态数据
  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });
  const getListType = ref(1);

  // 新建销售订单
  const add = () => {
    router.push({
      name: 'SalesOrderAdd',
    });
  };

  // 获取对应列表信息
  const getData = async (pageData?: any) => {
    try {
      let msg: any = {};
      if (NumberSearch.value) msg.number = NumberSearch.value;
      if (clientCompanyNameVal.value)
        msg.clientCompanyName = clientCompanyNameVal.value;
      if (StateVal.value) msg.state = StateVal.value;
      if (getListType.value) msg.state = getListType.value;

      const res = await GetClientOrder({
        ...pageData,
        ...msg,
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // // 修改对应的订单状态列表
  // const searchState = (key: number) => {
  //   userState.value = key;
  //   tableRef.value.loadData();
  // };

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const Search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  // 重置按钮
  const reset = () => {
    NumberSearch.value = '';
    clientCompanyNameVal.value = '';
    StateVal.value = '';
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        listType: getListType.value,
        extend: JSON.stringify(val),
      };
      await putHeaderSettings(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const affirm = (record: any, key: string) => {
    router.push({
      name: 'SalesOrderDetail',
      query: {
        id: record.id,
        key,
      },
    });
  };

  // 前往订单详情或者订单档案
  const goDetail = (id: any, state: number) => {
    // 前往订单详情
    if (state === 1) {
      router.push({
        name: 'SalesOrderDetail',
        query: {
          id,
        },
      });
    }
    // 前往订单档案
    else {
      router.push({
        name: 'SalesFileDetail',
        query: {
          id,
        },
      });
    }
  };

  const columns = [
    {
      name: '销售订单编号',
      code: 'number',
      isDefault: 1,
    },
    {
      name: '客户名称',
      code: 'clientCompanyName',
      isDefault: 1,
    },
    {
      name: '客户联系人',
      code: 'customerName',
      isDefault: 1,
    },
    {
      name: '客户联系电话',
      code: 'customerPhone',
      isDefault: 1,
    },
    {
      name: '业务员',
      code: 'userStaffName',
      isDefault: 1,
    },
    {
      name: '订单总金额',
      code: 'totalPrice',
      isDefault: 1,
    },
    {
      name: '订单创建时间',
      code: 'createdAt',
      isDefault: 1,
    },
    {
      name: '关联需求编号',
      code: 'demandNumber',
      isDefault: 1,
    },
  ];

  // 获取表头数据
  const headerSettingData = async (listType = 1) => {
    try {
      const res = await GetHeaderSettings({ listType });
      if (res.extends !== null) {
        headerSetting.list = res.extends;
      } else {
        headerSetting.list = columns;
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const getSearchType = (key: any) => {
    getListType.value = key;
    tableRef.value.loadData();
    isShow.value = !!key;
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const putOrderState = async (record: any, key: number) => {
    record.state = key;
    await putClientOrder(record);
    tableRef.value.loadData();
  };

  const stop = async (record: any) => {
    record.state = 4;
    await putClientOrder(record);
    tableRef.value.loadData();
  };

  const deleteItem = async (id: number) => {
    await DeleteClientOrder({ id });
    tableRef.value.loadData();
  };

  const OrderDerive = async () => {
    GetOrderDeriveExcel();
  };

  const modOrderState = async () => {
    await modState({ ids: tableRef.value.selectedKeys });
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  // .sales-order {
  // }
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }
  :deep(.arco-drawer-header) {
    background-color: rgb(232, 237, 250);
  }
</style>
